/*
* Copyright 2010 Dovado FZ-LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#import "InfoViewController.h"
#import "InfoTableViewCell.h"
#import "Info.h"
#import "DovadoAppDelegate.h"
#import "DialogUtils.h"

#define DARK_BACKGROUND  [UIColor colorWithRed:211.0/255.0 green:212.0/255.0 blue:215.0/255.0 alpha:1.0]
#define LIGHT_BACKGROUND [UIColor colorWithRed:242.0/255.0 green:243.0/255.0 blue:245.0/255.0 alpha:1.0]

@implementation InfoViewController
@synthesize mNetworkRequest;
@synthesize mGeneralArray;
@synthesize mConnectionArray;
@synthesize mTrafficArray;
@synthesize mPositionArray;
@synthesize mMiscArray;
@synthesize mToolbarTitle;

typedef enum {
	INFO_SECTION_GENERAL = 0,
	INFO_SECTION_CONNECTION,
	INFO_SECTION_TRAFFIC,
	INFO_SECTION_POSITIONING,
	INFO_SECTION_MISC,
	INFO_SECTION_COUNT
} InfoSections_t;



/*
 * Starts the download of available information from the router.
 */
- (void) syncAllData {	
	request_error_codes_t errorCode = [mNetworkRequest requestSyncAll];
	if (errorCode == REQUEST_OK) {
		mProgressAlert = [DialogUtils createProgressionAlertWithTitle:NSLocalizedString(@"synching_aliases_alert_title", @"Please wait") 
														   andMessage: NSLocalizedString(@"synching_aliases_alert_message", @"Downloading available aliases")];
	} else {
		[DialogUtils showConnectionFailedDialog:errorCode];
	}
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	mGeneralArray = NULL;
	mConnectionArray = NULL;
	mTrafficArray = NULL;
	mPositionArray = NULL;
	mMiscArray = NULL;
	mToolbarTitle.text = @"Info";
	mNetworkRequest = NULL;
}


- (IBAction) onRefreshButtonClicked {
	NSLog(@"InfoView : onRefreshButtonClicked");
	if (mNetworkRequest != NULL) {
		request_error_codes_t errorCode = [mNetworkRequest requestInfo];
		if (errorCode == REQUEST_OK) {
			mProgressAlert = [DialogUtils createProgressionAlertWithTitle:NSLocalizedString(@"info_dialog_title", @"Please wait") 
															   andMessage: NSLocalizedString(@"info_dialog_message", @"Downloading router information")];	
		} else {
			[DialogUtils showConnectionFailedDialog:errorCode];
		}
	} else {
		NSLog(@"mNetworkRequest is NULL");
	}
}

- (IBAction) onLoginButtonClicked {
	DovadoAppDelegate *appDelegate = (DovadoAppDelegate*) [[UIApplication sharedApplication] delegate];
	[appDelegate.window addSubview:appDelegate.mLoginViewController.view];
    [appDelegate.window makeKeyAndVisible];
}

- (void) parseInfoArray: (NSMutableArray*) infoArray {
	// Read the GPS lat/lon from the router. 
	DovadoAppDelegate *appDelegate = (DovadoAppDelegate*) [[UIApplication sharedApplication] delegate];
	CLLocationCoordinate2D coords;
	coords.latitude = appDelegate.mRouterLocation.latitude;
	coords.longitude = appDelegate.mRouterLocation.longitude;
	NSMutableArray *tmpGeneralArray = [[NSMutableArray alloc] init];
	NSMutableArray *tmpConnectionArray = [[NSMutableArray alloc] init];
	NSMutableArray *tmpTrafficArray = [[NSMutableArray alloc] init];
	NSMutableArray *tmpPositionArray = [[NSMutableArray alloc] init];
	NSMutableArray *tmpMiscArray = [[NSMutableArray alloc] init];
	for(Info *info in infoArray) {
		if([info.mName isEqualToString:@"Firmware_Revision"]) {
			[tmpGeneralArray addObject:info];
		} else if([info.mName isEqualToString:@"API_version"]) {
			[tmpGeneralArray addObject:info];
		} else if([info.mName isEqualToString:@"PRODUCT_NAME"]) {
			if([info.mValue isEqualToString:@"Dovado UMR"]) {
				appDelegate.router = ROUTER_UMR;
			} else if([info.mValue isEqualToString:@"Dovado 4GR"]) {
				appDelegate.router = ROUTER_4GR;
			} else {
				appDelegate.router = ROUTER_3GN;
			}
			[tmpGeneralArray addObject:info];
		} else if([info.mName isEqualToString:@"CONNECTION"]) {
			[tmpConnectionArray addObject:info];
		} else if([info.mName isEqualToString:@"EXTERNAL_IP"]) {
			[tmpConnectionArray addObject:info];
		} else if([info.mName isEqualToString:@"SIGNAL_STRENGTH"]) {
			[tmpConnectionArray addObject:info];
		} else if([info.mName isEqualToString:@"TRAFFIC_MODEM_TX"]) {
			[tmpTrafficArray addObject:info];
		} else if([info.mName isEqualToString:@"TRAFFIC_MODEM_RX"]) {
			[tmpTrafficArray addObject:info];
		} else if([info.mName isEqualToString:@"TRAFFIC_WAN_TX"]) {
			[tmpTrafficArray addObject:info];
		} else if([info.mName isEqualToString:@"TRAFFIC_WAN_RX"]) {
			[tmpTrafficArray addObject:info];
		} else if([info.mName isEqualToString:@"GPS_TYPE"]) {
			[tmpPositionArray addObject:info];
		} else if([info.mName isEqualToString:@"GPS_LAT"]) {
			coords.latitude = [info.mValue floatValue];
			[tmpPositionArray addObject:info];
		} else if([info.mName isEqualToString:@"GPS_LONG"]) {
			coords.longitude = [info.mValue floatValue];
			[tmpPositionArray addObject:info];
		} else if([info.mName isEqualToString:@"SUNRISE"]) {
			[tmpPositionArray addObject:info];
		} else if([info.mName isEqualToString:@"SUNSET"]) {
			[tmpPositionArray addObject:info];
		} else if([info.mName isEqualToString:@"DATE"]) {
			[tmpMiscArray addObject:info];
		} else if([info.mName isEqualToString:@"TIME"]) {
			[tmpMiscArray addObject:info];
		} else if([info.mName isEqualToString:@"SMS_UNREAD"]) {
			[tmpMiscArray addObject:info];
		} else if([info.mName isEqualToString:@"SMS_TOTAL"]) {
			[tmpMiscArray addObject:info];
		} else if([info.mName isEqualToString:@"CONNECTED_DEVICES"]) {
			[tmpMiscArray addObject:info];
		}
	}
	appDelegate.mRouterLocation = coords;
	
	if (mGeneralArray != nil) {
		[mGeneralArray release];
	}
	mGeneralArray = tmpGeneralArray;
	if (mConnectionArray != nil) {
		[mConnectionArray release];
	}
	mConnectionArray = tmpConnectionArray;
	if (mTrafficArray != nil) {
		[mTrafficArray release];
	}
	mTrafficArray = tmpTrafficArray;
	if (mPositionArray != nil) {
		[mPositionArray release];
	}
	mPositionArray = tmpPositionArray;
	if (mMiscArray != nil) {
		[mMiscArray release];
	}
	mMiscArray = tmpMiscArray;
}

- (void) viewDidAppear:(BOOL)animated {
	NSLog(@"viewDidAppear");
	[super viewDidAppear:(BOOL)animated];
	DovadoAppDelegate *appDelegate = (DovadoAppDelegate*) [[UIApplication sharedApplication] delegate];
	
	if (mNetworkRequest == NULL) {
		mNetworkRequest = [[DovadosNetworkRequest alloc] initWithHost: appDelegate.mHostAddress :6435];
	} else {
		[mNetworkRequest setMHost:appDelegate.mHostAddress];
	}
	[mNetworkRequest setUserInformation:appDelegate.mUser :appDelegate.mPassword: self];
	
	[self parseInfoArray:appDelegate.mInfoArray];
	[mTableView reloadData];
}

- (void) infoRequestDone: (NSMutableArray*) infoArray {
	DovadoAppDelegate *appDelegate = (DovadoAppDelegate*) [[UIApplication sharedApplication] delegate];
	[self parseInfoArray: infoArray];
	appDelegate.mInfoArray = infoArray;
	[mTableView reloadData];
		
	[DialogUtils dismissAlert:mProgressAlert];
	mProgressAlert = NULL;	
}

- (void) dovadoRequestFailed: (request_listener_error_t) error_code: (NSString*) message {
	NSLog(@"dovadoRequestFailed error_code: %i message: %@", error_code, message);
	[DialogUtils dismissAlert:mProgressAlert];
	mProgressAlert = NULL;
	if(error_code == ERROR_UNKNOWN_ERROR) {
		UIAlertView *errorAlert = [[UIAlertView alloc]
								   initWithTitle: NSLocalizedString(@"on_result_exception_dialog_title", @"Network Error")
								   message: NSLocalizedString(@"error_unknown_error", @"Unknown error")
								   delegate:self
								   cancelButtonTitle:NSLocalizedString(@"no_button_text", @"No")
								   otherButtonTitles:NSLocalizedString(@"yes_button_text", @"Yes"), nil];
		((UILabel*)[[errorAlert subviews] objectAtIndex:1]).textAlignment = UITextAlignmentLeft;
		[errorAlert show];
		[errorAlert release];
	} else {
		[DialogUtils showOnConnectionResultErrorDialog:error_code];
	}
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return INFO_SECTION_COUNT;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section
	NSInteger retVal = 0;
	switch (section) {
		case INFO_SECTION_GENERAL:
			retVal = [mGeneralArray count];
			break;
		case INFO_SECTION_CONNECTION:
			retVal = [mConnectionArray count];
			break;
		case INFO_SECTION_TRAFFIC:
			retVal = [mTrafficArray count];
			break;
		case INFO_SECTION_POSITIONING:
			retVal = [mPositionArray count];
			break;
		case INFO_SECTION_MISC:
			retVal = [mMiscArray count];
			break;
		default:
			NSLog(@"Error - tried to access non-existant group!");
			retVal = 0;
			break;
	}
	
	return retVal;
}

-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section; {	
	NSString* retVal = NULL;
	switch (section) {
		case INFO_SECTION_GENERAL:
			if ([mGeneralArray count]>0) {
				retVal = NSLocalizedString(@"info_general_section", @"General");
			}
			break;
		case INFO_SECTION_CONNECTION:
			if ([mConnectionArray count]>0) {
				retVal = NSLocalizedString(@"info_connections_section", @"Connections");
			}
			break;
		case INFO_SECTION_TRAFFIC:
			if ([mTrafficArray count]>0) {
				retVal = NSLocalizedString(@"info_traffic_section", @"Traffic");
			}
			break;
		case INFO_SECTION_POSITIONING:
			if ([mPositionArray count]>0) {
				retVal = NSLocalizedString(@"info_positioning_section", @"Positioning");
			}
			break;
		case INFO_SECTION_MISC:
			if ([mMiscArray count]>0) {
				retVal = NSLocalizedString(@"info_misc_section", @"Misc");
			}
			break;
		default:
			NSLog(@"Error - tried to access non-existant group!");
			retVal = 0;
			break;
	}
	return retVal;
}

/*
 * Loads an OnOffTableCell from a nib-file.
 */
- (InfoTableViewCell *) loadInfoTableCell {
	InfoTableViewCell *infoCell;
	NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"InfoTableViewCell" owner:self options:nil];	
	for(id currentNibObj in nib) {
		if ([currentNibObj isKindOfClass:[InfoTableViewCell class]]) {
			infoCell = (InfoTableViewCell*) currentNibObj;
			break;
		}				
	}
	return infoCell;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *infoCellIdentifier = @"InfoTableViewCell";
	InfoTableViewCell *infoCell = NULL;
    
	infoCell = (InfoTableViewCell *) [tableView dequeueReusableCellWithIdentifier:infoCellIdentifier];
	if (infoCell == nil) {
		infoCell = [self loadInfoTableCell];
		//cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:generalCellIdentifier] autorelease];
		infoCell.selectionStyle = UITableViewCellSelectionStyleNone;
	}
	
	Info *info= NULL;
	switch (indexPath.section) {
		case INFO_SECTION_GENERAL:
			info = [mGeneralArray objectAtIndex:indexPath.row];
			break;
		case INFO_SECTION_CONNECTION:
			info = [mConnectionArray objectAtIndex:indexPath.row];
			break;
		case INFO_SECTION_TRAFFIC:
			info = [mTrafficArray objectAtIndex:indexPath.row];
			break;
		case INFO_SECTION_POSITIONING:
			info = [mPositionArray objectAtIndex:indexPath.row];
			break;
		case INFO_SECTION_MISC:
			info = [mMiscArray objectAtIndex:indexPath.row];
			break;
		default:
			NSLog(@"Error - tried to access non-existant group!");
			info = NULL;
			break;
	}
	
	if(info != NULL) {
		/* Set more readable names for the info */
		if([info.mName isEqualToString:@"Firmware_Revision"]) {
			infoCell.mNameLabel.text = @"Router Firmware";
			infoCell.mValueLabel.text = info.mValue;
		} else if([info.mName isEqualToString:@"API_version"]) {
			infoCell.mNameLabel.text = @"API Version";
			infoCell.mValueLabel.text = info.mValue;
		} else if([info.mName isEqualToString:@"PRODUCT_NAME"]) {			
			infoCell.mNameLabel.text = @"Product Name";
			infoCell.mValueLabel.text = info.mValue;
		} else if([info.mName isEqualToString:@"CONNECTION"]) {
			infoCell.mNameLabel.text = @"Current connection type";
			infoCell.mValueLabel.text = info.mValue;
		} else if([info.mName isEqualToString:@"EXTERNAL_IP"]) {
			infoCell.mNameLabel.text = @"External IP address";
			infoCell.mValueLabel.text = info.mValue;
		} else if([info.mName isEqualToString:@"SIGNAL_STRENGTH"]) {
			infoCell.mNameLabel.text = @"Modem signal strength";
			if([info.mValue isEqualToString:@"-"]) {
				infoCell.mValueLabel.text = @"Not available";
			} else {
				infoCell.mValueLabel.text = [NSString stringWithFormat:@"%@%%", info.mValue];
			}
		} else if([info.mName isEqualToString:@"TRAFFIC_MODEM_TX"]) {
			infoCell.mNameLabel.text = @"Transmitted Modem";
			if([info.mValue isEqualToString:@"NA"]) {
				infoCell.mValueLabel.text = @"Not available";
			} else {
				int val = [info.mValue intValue];
				if(val != 0) {
					val = val / 1000;
				}
				infoCell.mValueLabel.text = [NSString stringWithFormat:@"%d MB", val];
			}
		} else if([info.mName isEqualToString:@"TRAFFIC_MODEM_RX"]) {
			infoCell.mNameLabel.text = @"Received Modem";
			if([info.mValue isEqualToString:@"NA"]) {
				infoCell.mValueLabel.text = @"Not available";
			} else {
				int val = [info.mValue intValue];
				if(val != 0) {
					val = val / 1000;
				}
				infoCell.mValueLabel.text = [NSString stringWithFormat:@"%d MB", val];
			}
		} else if([info.mName isEqualToString:@"TRAFFIC_WAN_TX"]) {
			infoCell.mNameLabel.text = @"Transmitted Ethernet";
			if([info.mValue isEqualToString:@"NA"]) {
				infoCell.mValueLabel.text = @"Not available";
			} else {
				int val = [info.mValue intValue];
				if(val != 0) {
					val = val / 1000;
				}
				infoCell.mValueLabel.text = [NSString stringWithFormat:@"%d MB", val];
			}
		} else if([info.mName isEqualToString:@"TRAFFIC_WAN_RX"]) {
			infoCell.mNameLabel.text = @"Received Ethernet";
			if([info.mValue isEqualToString:@"NA"]) {
				infoCell.mValueLabel.text = @"Not available";
			} else {
				int val = [info.mValue intValue];
				if(val != 0) {
					val = val / 1000;
				}
				infoCell.mValueLabel.text = [NSString stringWithFormat:@"%d MB", val];
			}
		} else if([info.mName isEqualToString:@"GPS_TYPE"]) {
			infoCell.mNameLabel.text = @"Positioning type";
			infoCell.mValueLabel.text = info.mValue;
		} else if([info.mName isEqualToString:@"GPS_LAT"]) {
			infoCell.mNameLabel.text = @"Latitude";
			infoCell.mValueLabel.text = info.mValue;
		} else if([info.mName isEqualToString:@"GPS_LONG"]) {
			infoCell.mNameLabel.text = @"Longitude";
			infoCell.mValueLabel.text = info.mValue;
		} else if([info.mName isEqualToString:@"SUNRISE"]) {
			infoCell.mNameLabel.text = @"Sunrise at current position";
			infoCell.mValueLabel.text = info.mValue;
		} else if([info.mName isEqualToString:@"SUNSET"]) {
			infoCell.mNameLabel.text = @"Sunset at current position";
			infoCell.mValueLabel.text = info.mValue;
		} else if([info.mName isEqualToString:@"DATE"]) {
			infoCell.mNameLabel.text = @"Current date";
			infoCell.mValueLabel.text = info.mValue;
		} else if([info.mName isEqualToString:@"TIME"]) {
			infoCell.mNameLabel.text = @"Current time";
			infoCell.mValueLabel.text = info.mValue;
		} else if([info.mName isEqualToString:@"SMS_UNREAD"]) {
			infoCell.mNameLabel.text = @"Number of unread SMS";
			infoCell.mValueLabel.text = info.mValue;
		} else if([info.mName isEqualToString:@"SMS_TOTAL"]) {
			infoCell.mNameLabel.text = @"Number of SMS in inbox";
			infoCell.mValueLabel.text = info.mValue;
		} else if([info.mName isEqualToString:@"CONNECTED_DEVICES"]) {
			infoCell.mNameLabel.text = @"Connected devices";
			infoCell.mValueLabel.text = info.mValue;
		} else {
			return NULL;
		}
		
		infoCell.mNameLabel.font = [UIFont boldSystemFontOfSize:12];
		infoCell.mValueLabel.font = [UIFont systemFontOfSize:12];
		
		//cell.textLabel.text = [NSString stringWithFormat:@"%@: %@", info.mName, info.mValue];
	}
	
    return (UITableViewCell *) infoCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
	/*
	if((indexPath.row%2) == 0) {
		cell.backgroundColor = LIGHT_BACKGROUND;
	} else {
		cell.backgroundColor = DARK_BACKGROUND;
	}
	 */
}


- (void) syncAllRequestDone: (NSMutableArray*) groupsArray: (NSMutableArray*) aliasArray: (NSMutableArray*) infoArray {
	DovadoAppDelegate *appDelegate = (DovadoAppDelegate*)[[UIApplication sharedApplication] delegate];
	if (groupsArray != NULL) {
		NSMutableArray *tmpGroupsArray = [[NSMutableArray alloc] init];
		for(Info *group in groupsArray) {
			[tmpGroupsArray addObject:group];
		}
		if (appDelegate.mGroupsArray != NULL) {
			[appDelegate.mGroupsArray release];
		}
		appDelegate.mGroupsArray = tmpGroupsArray;
	}
	
	if (aliasArray != NULL) {
		NSMutableArray *tmpAliasArray = [[NSMutableArray alloc] init];
		for(Info *alias in aliasArray) {
			[tmpAliasArray addObject:alias];
		}
		if (appDelegate.mAliasArray != NULL) {
			[appDelegate.mAliasArray release];
		}
		appDelegate.mAliasArray = tmpAliasArray;
	}
	
	if (infoArray != NULL) {
		[self parseInfoArray: infoArray];
		[mTableView reloadData];
	}
	
	/* Login was correct, now store the username, password and hostname */
	[appDelegate storeSharedPrefs];
	
	[DialogUtils dismissAlert:mProgressAlert];
	mProgressAlert = NULL;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[mProgressAlert release];
	[mNetworkRequest release];
	[mGeneralArray release];
	[mConnectionArray release];
	[mTrafficArray release];
	[mPositionArray release];
	[mMiscArray release];
	[mTableView release];
	[mToolbarTitle release];
    [super dealloc];
}

@end
